package com.example.day03;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jeff
* @since 2023/5/1 16:46
 */
public class ConstantEnumConverterFactory implements ConverterFactory<String, ConstantEnumIFace> {
    Map<Class,StringToEnumConverter> enumMap = new HashMap<>();
	public ConstantEnumConverterFactory() {
    }

    @Override
    public <T extends ConstantEnumIFace> Converter<String, T> getConverter(Class<T> targetType) {
        StringToEnumConverter stringToEnumConverter = enumMap.get(targetType);
        if (null==stringToEnumConverter) {
            stringToEnumConverter = new StringToEnumConverter(targetType);
            enumMap.put(targetType,stringToEnumConverter);
        }
        return stringToEnumConverter;
    }

    private static class StringToEnumConverter<T extends ConstantEnumIFace<T>> implements Converter<String, T> {
        private T firstEnum;

        public StringToEnumConverter(Class<T> enumType) {
            firstEnum=enumType.getEnumConstants()[0];
        }

        @Override
        public T convert(String sourceStr) {
            return firstEnum.theEnum(Integer.parseInt(sourceStr));
        }
    }
}
